package es.uji.icc.robot.grasp;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Element;
import org.xml.sax.SAXException;


/**
 * 
 * Stores the response of the robot server. As the robot is a REST server and it
 * returns values in XML this class is responsible to store that XML, but also
 * provide functionality to transform the XML in other class ( as Joints)
 * 
 */
@XmlRootElement(name="GraspResponse",namespace="")
public class GraspResponse {

	private String xml;
	
	private String message;
	private int status;

	public GraspResponse(String s) throws GraspResponseException {
		xml = s;
		parseXML();
	}

	public GraspResponse() {

	}

	
	public String getXml() {
		return xml;
	}

	public void setXml(String xml) throws GraspResponseException {
		this.xml = xml;
		parseXML();
	}

	
	public int getStatus() {
		return status;
	}

	public void setStatus(int status) {
		this.status = status;
	}

	public String getMessage() {
		 return this.message;	
	}


	
	
	
	protected void parseXML() throws GraspResponseException
	{
		Element node;
		String xml = this.getXml();
		try {
			node = DocumentBuilderFactory.newInstance().newDocumentBuilder()
					.parse(new ByteArrayInputStream(xml.getBytes())).getDocumentElement();
			message = node.getElementsByTagName("message").item(0).getFirstChild().getNodeValue();			
		} catch (SAXException e) {
			throw new GraspResponseException(e.getMessage());
		} catch (IOException e) {
			throw new GraspResponseException(e.getMessage());
		} catch (ParserConfigurationException e) {
			throw new GraspResponseException(e.getMessage());
		}
		
				
	}
	
	
		
	public void setMessage(String message) {
		this.message = message;
	}
	
	


	
	

	
}
